<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Model\User;
use Hyperf\Utils\Context;
use Phper666\JwtAuth\Exception\TokenValidException;
use Phper666\JwtAuth\Jwt;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Hyperf\Di\Annotation\Inject;
use Psr\Http\Server\RequestHandlerInterface;

class UserJwtGetMiddleware implements MiddlewareInterface
{
    /**
     * @Inject
     * @var ServerRequestInterface
     */
    protected $request;

    /**
     * @Inject
     * @var Jwt
     */
    protected $jwt;

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        try {
            $token = $this->jwt->getTokenObj();
            if ($this->jwt->checkToken()) {
                $userId = $token->getClaim('user_id');
                $user = User::where('union_id', $userId)->first();
                if (!$user) {
                    throw new TokenValidException('Token未验证通过', 401);
                }
                $request = $request->withAttribute('user', $user);
                Context::set(ServerRequestInterface::class, $request);
            }
        } catch (\Exception $e) {
        }
        return $handler->handle($request);
    }
}